<template>
  <div class="page-container">
    <Header />
    <div class="login-container">
      <div class="login-box">
        <div class="login-header">
          <h2>心理咨询服务平台</h2>
          <p>专业倾听，温暖守护</p>
        </div>
        
        <div class="switch-form">
          <el-radio-group v-model="activeForm" size="large">
            <el-radio-button label="clientLogin">咨询者登录</el-radio-button>
            <el-radio-button label="counselorLogin">咨询师登录</el-radio-button>
            <el-radio-button label="register">注册</el-radio-button>
          </el-radio-group>
        </div>
        
        <div class="login-form" v-if="activeForm === 'clientLogin'">
          <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
            <el-form-item prop="userid">
              <el-input 
                v-model="loginForm.userid"
                prefix-icon="User"
                placeholder="请输入用户ID">
              </el-input>
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input 
                v-model="loginForm.password"
                prefix-icon="Lock"
                type="password"
                :show-password="true"
                placeholder="请输入密码">
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" class="login-button" @click="handleClientLogin">
                登录
              </el-button>
            </el-form-item>
          </el-form>

          <div class="login-options">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <a href="#">忘记密码？</a>
          </div>
        </div>

        <div class="login-form" v-if="activeForm === 'counselorLogin'">
          <el-form :model="counselorLoginForm" :rules="loginRules" ref="counselorFormRef">
            <el-form-item prop="doctorid">
              <el-input 
                v-model="counselorLoginForm.doctorid"
                prefix-icon="User"
                placeholder="请输入咨询师ID">
              </el-input>
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input 
                v-model="counselorLoginForm.password"
                prefix-icon="Lock"
                type="password"
                :show-password="true"
                placeholder="请输入密码">
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" class="login-button" @click="handleCounselorLogin">
                登录
              </el-button>
            </el-form-item>
          </el-form>

          <div class="login-options">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <a href="#">忘记密码？</a>
          </div>
        </div>

        <div class="register-form" v-if="activeForm === 'register'">
          <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef">
            <el-form-item prop="name">
              <el-input 
                v-model="registerForm.name"
                prefix-icon="User"
                placeholder="请输入姓名">
              </el-input>
            </el-form-item>
            
            <el-form-item prop="gender">
              <div class="form-label">性别：</div>
              <el-radio-group v-model="registerForm.gender">
                <el-radio label="male">男</el-radio>
                <el-radio label="female">女</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item prop="age">
              <div class="form-label">年龄：</div>
              <el-input-number 
                v-model="registerForm.age"
                :min="1"
                :max="120"
                controls-position="right"
                class="age-input"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input 
                v-model="registerForm.password"
                prefix-icon="Lock"
                type="password"
                :show-password="true"
                placeholder="请输入密码">
              </el-input>
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input 
                v-model="registerForm.confirmPassword"
                prefix-icon="Lock"
                type="password"
                :show-password="true"
                placeholder="请确认密码">
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" class="submit-button" @click="handleRegister">
                注册
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { User, Lock, Message } from '@element-plus/icons-vue'
import Header from '../components/header.vue'
import Footer from '../components/footer.vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { login, register, clientLogin, doctorLogin } from '../api/auth'

const router = useRouter()
const activeForm = ref('clientLogin')
const loginFormRef = ref<FormInstance>()
const counselorFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()
const rememberMe = ref(false)

// 咨询者登录表单数据
const loginForm = reactive({
  userid: '',
  password: ''
})

// 咨询师登录表单数据
const counselorLoginForm = reactive({
  doctorid: '',
  password: ''
})

// 注册表单数据
const registerForm = reactive({
  name: '',
  gender: 'male',
  age: 18,
  password: '',
  confirmPassword: ''
})

// 验证确认密码
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 登录表单验证规则
const loginRules = reactive<FormRules>({
  doctorid: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { pattern: /^\d+$/, message: 'ID必须为数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 5, message: '密码长度在3到5个字符', trigger: 'blur' }
  ]
})

// 注册表单验证规则
const registerRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 120, message: '年龄必须在1-120岁之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 5, message: '密码长度在3到5个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 处理注册
const handleRegister = () => {
  registerFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const res = await register({
          name: registerForm.name,
          sex: registerForm.gender === 'male' ? 1 : 0,
          age: registerForm.age,
          password: registerForm.password
        })
        
        // 注册成功后自动登录
        if (res.code === '200') {
          // 输出返回的用户信息
          console.log('注册返回数据:', res)
          console.log('用户数据:', res.data)
          
          // 保存用户信息
          localStorage.setItem('userid', res.data.id)
          localStorage.setItem('username', registerForm.name)
          localStorage.setItem('userRole', 'client')
          localStorage.setItem('sex', String(registerForm.gender === 'male' ? 1 : 0))
          localStorage.setItem('age', String(registerForm.age))
          
          ElMessage.success('注册成功！')
          router.push('/user/dashboard')  // 直接进入个人中心
        } else {
          ElMessage.error(res.msg || '注册失败')
        }
      } catch (error: any) {
        ElMessage.error(error.message || '注册失败')
      }
    }
  })
}

// 处理咨询者登录
const handleClientLogin = () => {
  loginFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const res = await clientLogin({
          userid: parseInt(loginForm.userid),
          password: loginForm.password
        })
        
        // 检查返回的状态码
        if (res.code === '200') {
          // 保存用户信息
          localStorage.setItem('userid', res.data.clientId)
          localStorage.setItem('username', res.data.name)
          localStorage.setItem('userRole', 'user')
          localStorage.setItem('email', res.data.email)
          
          ElMessage.success(res.msg || '登录成功')
          router.push('/user/dashboard')
        } else {
          console.log('登录失败:', res)
          ElMessage.error(res.msg || '登录失败')
        }
      } catch (error: any) {
        console.error('登录错误:', error)
        ElMessage.error(error.message || '登录失败')
      }
    }
  })
}

// 处理咨询师登录
const handleCounselorLogin = () => {
  counselorFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const res = await doctorLogin({
          doctorid: parseInt(counselorLoginForm.doctorid),
          password: counselorLoginForm.password
        })
        
        // 检查返回的状态码
        if (res.code === '200') {
          // 输出返回的用户信息
          console.log('医生登录返回数据:', res)
          console.log('医生数据:', res.data)
          
          // 保存用户信息
          localStorage.setItem('doctorid', String(res.data.doctorId))
          localStorage.setItem('username', res.data.name)
          localStorage.setItem('sex', String(res.data.sex))
          localStorage.setItem('age', String(res.data.age))
          localStorage.setItem('userRole', 'doctor')
          localStorage.setItem('email', res.data.email)
          // 处理并保存头像
          if (res.data.img) {
            const imageUrl = `data:image/jpeg;base64,${res.data.img}`
            localStorage.setItem('avatar', imageUrl)
          }
          
          ElMessage.success(res.msg || '登录成功')
          router.push({
            name: 'DoctorDashboard',
            params: { id: res.data.doctorid }
          })
        } else {
          console.log('医生登录失败:', res)
          ElMessage.error(res.msg || '登录失败')
        }
      } catch (error: any) {
        console.error('医生登录错误:', error)
        ElMessage.error(error.message || '登录失败')
      }
    }
  })
}

// ... 其他代码保持不变 ...
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #e0f2f1 0%, #e8f5e9 100%);
  display: flex;
  flex-direction: column;
}

.login-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 64px 0;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.login-header p {
  color: #7f8c8d;
  font-size: 14px;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
  padding: 12px 0;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  font-size: 14px;
}

.login-options a {
  color: #409EFF;
  text-decoration: none;
}

.login-options a:hover {
  text-decoration: underline;
}

.user-type-group {
  width: 100%;
  display: flex;
  justify-content: center;
  margin: 10px 0;
}

.login-form :deep(.el-radio) {
  margin-right: 30px;
}

.login-form :deep(.el-radio:last-child) {
  margin-right: 0;
}

.switch-form {
  text-align: center;
  margin-bottom: 30px;
}

.register-form {
  margin-top: 20px;
}

.form-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.register-form :deep(.el-radio-group) {
  display: flex;
  justify-content: flex-start;
  gap: 30px;
}

.register-form :deep(.el-radio) {
  margin-right: 0;
}

.age-input {
  width: 120px !important;
}

.age-input :deep(.el-input-number__decrease),
.age-input :deep(.el-input-number__increase) {
  border-left: 1px solid #dcdfe6;
}

.age-input :deep(.el-input__wrapper) {
  padding-left: 12px;
}

.submit-button {
  width: 100%;
  padding: 12px 0;
}

:deep(.el-radio-group) {
  width: 100%;
  display: flex;
  justify-content: center;
}

:deep(.el-radio-button__inner) {
  width: 100px;
}
</style>